import { View } from "@tarojs/components"
import Taro, { getStorageSync, useDidShow } from "@tarojs/taro"
import { useEffect, useState } from "react"
import { AtIcon } from "taro-ui"


const Collection = props => {
    //用于收藏键的状态
    const [isRight, setOpen2] = useState(true)
    // 保存触发收藏事件的数据
    const recommendedList = props.data
    console.log("详细页面中的数据：", recommendedList)
    // console.log("id:",Taro.getStorageSync("openid") + recommendedList[0]._id)
    useEffect(() => {
        Taro.cloud.callFunction({
            // 云函数名称(对每日推荐进行数据提取，后续会分板块进行数据的提取)
            name: 'collection',
            data: {
                // $url:"find_recommended",
                event: "find_recommended",
                logotype: Taro.getStorageSync("openid") + recommendedList[0]._id
            }
        }).then(res => {
            console.log("res.result:", res.result)
            if (res.result.data.length!==0) {
                setOpen2(!isRight)
            }
        })
    },[props])
    const changeRight = () => {
        // 首先先改边收藏的状态，通过改变颜色
        setOpen2(!isRight)
        //获取缓存中的用户部分信息，以便后续对数据的精准控制
        const user = getStorageSync("userInfo")
        if (isRight) {
            // 调用云函数进行对数据的保存(收藏成功)
            Taro.cloud.callFunction({
                name: "collection",
                data: {
                    $url: "add_collection",
                    collection_person: user.nickName,
                    title: recommendedList[0].recommended_title,
                    content: recommendedList[0].recommended_content,
                    picture: recommendedList[0].picture,
                    id: Taro.getStorageSync("openid") + recommendedList[0]._id,//通过openid于图片本身的id形成唯一id
                }
            }).then(() => {
                Taro.showToast({
                    title: '收藏成功',
                    icon: 'success',
                    duration: 1500,
                })
            })
        } else {
            //调用数据库进行数据的删除(取消收藏)
            Taro.cloud.callFunction({
                name: "collection",
                data: {
                    $url: "remove_collection",
                    id: Taro.getStorageSync("openid") + recommendedList[0]._id
                }
            }).then(() => {
                Taro.showToast({
                    title: '取消收藏',
                    icon: 'error',
                    duration: 1500,
                    mask: true,
                })
            })
        }
    }

    return (
        <View>
            <View onClick={() => { changeRight() }}>
                {
                    isRight ? (<AtIcon className="star" value='star-2' size='20' color='#000' />
                    ) : (
                        <AtIcon className="star" value='star-2' size='20' color='#cb4047' />
                    )
                }
            </View>
        </View>
    )
}

export default Collection
